import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/user_type_enum.dart';
import 'package:tracker/pages/profile/mixin/profile_page_mixin.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/toast_utils.dart';
import 'package:tracker/utils/upgrade_utils.dart';

/// 个人中心页面
class ProfilePage extends ConsumerStatefulWidget {
  const ProfilePage({super.key});

  @override
  ConsumerState<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends ConsumerState<ProfilePage> with AutomaticKeepAliveClientMixin, ProfilePageMixin {
  /// 保存页面状态
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  _onMenuItemTap(index) async {
    final userType = ref.watch(userTypeProvider);
    final menu = menuList[index];
    // 根据menu的code判断是什么操作
    switch (menu.code) {
      case 'bindDevice':
        if (userType == UserTypeEnum.device) {
          ToastUtils.showDeviceLoginDialog(context);
          return;
        }
        context.push(RouterManager.bindDevice);
        break;
      case 'unbindDevice':
        // 没有设备，提示
        await queryUserDeviceCount();
        if (userDeviceCount == 0) {
          _showNoDeviceDialog();
        } else {
          context.push(RouterManager.unbindDevice);
        }
        break;
      case 'order':
        context.push(RouterManager.order);
        break;
      case 'notificationSetting':
        if (userType == UserTypeEnum.device) {
          ToastUtils.showDeviceLoginDialog(context);
          return;
        }
        context.push(RouterManager.notificationSetting);
        break;
      case 'changePassword':
        context.push(RouterManager.changePasswordLogon);
        break;
      case 'customerService':
        context.push(RouterManager.customerService);
        break;
      case 'checkUpdate':
        // 检查更新
        UpgradeUtils.checkUpdateByManual(context, fromPage: 'profile');
        break;
      case 'userServiceAgreement':
        context.pushNamed('protocol',
            queryParameters: {'title': '用户协议', 'url': 'https://xjtl.tech/user_agreement/index.html'});
        break;
      case 'privacyPolicy':
        context.pushNamed('protocol',
            queryParameters: {'title': '隐私政策', 'url': 'https://xjtl.tech/privacy_policy/index.html'});
        break;
      case 'about':
        context.push(RouterManager.about);
        break;
      case 'logout':
        _logout();
        break;
    }
  }

  // 兼容旧命名
  _onMenuCellClick(index) async { await _onMenuItemTap(index); }

  _logout() {
    // 弹窗提示
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: const Text('提示'),
            content: const Text('确定要退出登录吗?'),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text(
                    '取消',
                    style: TextStyle(color: Colors.black),
                  )),
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    handleLogout();
                  },
                  child: const Text(
                    '确定',
                    style: TextStyle(color: Colors.red),
                  )),
            ],
          );
        });
  }

  /// 未绑定设备提示
  _showNoDeviceDialog() {
    showCupertinoDialog(
        context: context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: const Text('提示'),
            content: const Text('您未绑定任何设备'),
            actions: [
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text(
                    '取消',
                  )),
              TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    context.push(RouterManager.bindDevice);
                  },
                  child: const Text(
                    '去绑定',
                    style: TextStyle(color: Colors.red),
                  )),
            ],
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final userType = ref.watch(userTypeProvider);
    final userInfo = ref.watch(userInfoProvider);
    final deviceInfo = ref.watch(deviceInfoProvider);
    // 根据用户类型过滤菜单
    filterMenuList(userType);
    var userTypeStr = getLoginTypeName(userType);
    var username = getLoginName(userType, userInfo, deviceInfo);

    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          // 滚动不显示
          toolbarHeight: 0,
          systemOverlayStyle: SystemUiOverlayStyle.dark,
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        backgroundColor: ColorUtils.hexToColor('#ffffff'),
        body: Stack(
          children: [
            // 头像区
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Container(
                // color: Colors.white,
                width: double.infinity,
                height: 250,
                // 设置背景图
                decoration: const BoxDecoration(
                    image: DecorationImage(
                  image: AssetImage('assets/images/profile/profile_top@3x.png'),
                  fit: BoxFit.cover,
                )),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 头像图标
                    const Image(
                      image: AssetImage('assets/images/logo/xjww_logo.png'),
                      width: 80,
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Text(
                      username,
                      style: TextStyle(
                          color: AppTheme.themeConfig.secondaryTextColor, fontWeight: FontWeight.bold, fontSize: 20),
                    ),
                    // 登录类型
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      padding: const EdgeInsets.only(left: 10, right: 10),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [Colors.white, Colors.white.withOpacity(0.9)],
                        ),
                        borderRadius: BorderRadius.circular(20),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.08),
                            blurRadius: 6,
                            offset: const Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Text(
                        userTypeStr,
                        style: TextStyle(
                          color: AppTheme.themeConfig.infoTextColor,
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    // 手机号
                    if (userType == UserTypeEnum.device)
                      Container(
                        margin: const EdgeInsets.only(top: 10),
                        padding: const EdgeInsets.only(left: 10, right: 10),
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(20)),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              "绑定手机：${userInfo.phone ?? ''}",
                              style: TextStyle(color: AppTheme.themeConfig.infoTextColor, fontSize: 12),
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
            ),
            Positioned(
              top: 230,
              left: 0,
              right: 0,
              bottom: 0,
              child: Container(
                // margin: EdgeInsets.all(20),
                // margin: EdgeInsets.only(bottom: 20),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.06),
                      blurRadius: 12,
                      offset: const Offset(0, -4),
                    ),
                  ],
                ),
                height: menuList.length * 50 + menuList.length * 1.0,
                child: ListView.separated(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: const EdgeInsets.only(left: 20, right: 20),
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        onTap: () { _onMenuItemTap(index); },
                        child: _ProfileMenuItem(icon: menuList[index].icon, title: menuList[index].title),
                      );
                    },
                    separatorBuilder: (context, index) => const Divider(
                          height: 1,
                          indent: 35,
                        ),
                    itemCount: menuList.length),
              ),
            ),
            // 显示测试版
            if (Env.isTest())
              Positioned(
                bottom: 20,
                left: 0,
                right: 0,
                child: Container(
                  padding: const EdgeInsets.only(left: 10, right: 10),
                  alignment: Alignment.center,
                  child: Text(
                    '测试版(Build ${Env.envConfig.buildNumber})',
                    style: TextStyle(color: Colors.grey, fontSize: 18),
                  ),
                ),
              ),
          ],
        ));
  }
}
class _ProfileMenuItem extends StatelessWidget {
  final Widget icon;
  final String title;
  const _ProfileMenuItem({required this.icon, required this.title});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 4),
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      height: 56,
      width: double.infinity,
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(6),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Colors.orange.shade400.withOpacity(0.15),
                  Colors.orange.shade600.withOpacity(0.05),
                ],
              ),
              borderRadius: BorderRadius.circular(10),
            ),
            child: icon,
          ),
          const SizedBox(width: 14),
          Text(
            title,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: AppTheme.themeConfig.primaryTextColor,
            ),
          ),
          const Spacer(),
          Icon(
            Icons.chevron_right,
            color: AppTheme.themeConfig.infoTextColor,
            size: 20,
          ),
        ],
      ),
    );
  }
}
